package com.evision.webcrawler.baidu;

import org.apache.commons.io.IOUtils;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.util.UUID;

/**
 * author: ${yl}.
 * date: 17-11-11.
 * description: .
 */
public class ImgDownloadUtil {

    public static void imgDownload(String imgurl,String savePath){
        try {
            String suffix = imgurl.substring(imgurl.lastIndexOf("."));
            String outImage = UUID.randomUUID().toString().replaceAll("-", "")  + suffix;
            //创建连接
            if(!imgurl.contains("http")){
                //有些网站带http
                imgurl = "http:" + imgurl;
            }
            URL imgUrl = new URL(imgurl);
            //获取输入流
            InputStream inputStream = imgUrl.openConnection().getInputStream();


            //限制图片大小
            BufferedImage sourceImg = ImageIO.read(inputStream);
            int width = sourceImg.getWidth();
            int height = sourceImg.getWidth();
            if (width > 300 && height > 300) {
                //将输入流信息放入缓冲流提升读写速度

                IOUtils.copy(imgUrl.openConnection().getInputStream(), new FileOutputStream(savePath + outImage));

            }
        }catch (Exception e){

        }


    }
}
